// -----------------------------------------------------------------------
//  <copyright file="IUnitOfWork.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/7 0:53:50</last-date>
// -----------------------------------------------------------------------

namespace DaprPlus.Domain.Entity;

/// <summary>
/// 定义一个单元操作的功能，管理单元操作内涉及的所有上下文对象及其事务
/// </summary>
public interface IUnitOfWork : IDisposable
{
    /// <summary>
    /// 获取当前单元操作的数据上下文
    /// </summary>
    IDbContext DbContext { get; }

    /// <summary>
    /// 是否已提交事务
    /// </summary>
    bool HasCommitted { get; }

    /// <summary>
    /// 是否启用事务，如果没有启动事务，就使用默认的事务
    /// </summary>
    bool IsEnabledTransaction { get; }

    /// <summary>
    /// 启用事务，事务代码写在 UnitOfWork.EnableTransaction() 与 UnitOfWork.Commit() 之间
    /// </summary>
    void EnableTransaction();

    /// <summary>
    /// 对数据库连接开启事务
    /// </summary>
    /// <param name="token">异步取消标记</param>
    /// <returns></returns>
    Task BeginOrUseTransactionAsync(CancellationToken token = default);

    /// <summary>
    /// 提交当前上下文的事务更改
    /// </summary>
    /// <returns></returns>
    Task CommitAsync(CancellationToken token = default);

    /// <summary>
    /// 回滚所有事务
    /// </summary>
    /// <returns></returns>
    Task RollbackAsync(CancellationToken token = default);

    /// <summary>
    /// 添加集成事件，这些事件将在工作单元提交事务后发布
    /// </summary>
    /// <param name="events">集成事件</param>
    void AddIntegrationEvent(params IntegrationEvent[] events);
}
